<?php
namespace Modules\Common\Exports;

use Illuminate\Support\Facades\Cache;
use Modules\Production\Repository\ProductionOrderDetailRepository;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use App\Enums\ProductionOrderBackStatus;

class BackDetail{

    public function export($params){

        $exportData = ProductionOrderDetailRepository::getOrderDetail($params);
        //print_r($exportData);exit();

        $title = ['工单号','工艺流程','产品编码','产品名称','产品规格','产品型号','产品单位','物料编码','物料名称','领料状态','分子','分母','物料单位','应发数量','已领数量','创建时间'];

        $excelData = [];
        foreach ($exportData['data'] as &$item){
            $excelData[] = [
                $item['order']['fbillno'],
                $item['order']['flow_name'],
                $item['order']['fmaterialid'],
                $item['order']['fmaterialname'],
                $item['order']['fmaterialmodel'],
                $item['order']['fmodel'],
                $item['order']['funitid_name'],
                $item['fmaterialid1'],
                $item['fmaterialname1'],
                ProductionOrderBackStatus::labelBy($item['back_status']),
                $item['fnumerator'],
                $item['fdenominator'],
                $item['funitid1_name'],
                $item['fmustqty'],
                $item['fpickedqty'],
                $item['created_at'],
            ];
        }

        $jobId = isset($params['job_id']) && !empty($params['job_id']) ? $params['job_id'] : md5(microtime());

        $fileName = $this->saveExcel($jobId,$title,$excelData,$exportData['current_page']);

        $totalPage = ceil($exportData['total'] / $exportData['per_page']);

        $outData = [
            'job_id'        => $jobId,
            'total'         => $exportData['total'],
            'limit'         => $exportData['per_page'],
            'total_page'    => $totalPage,
            'page'          => $exportData['current_page'],
            'finish'        => 0,
            'excel_url'     => ''
        ];

        if($exportData['current_page'] == $totalPage){
            //最后一页
            $outData['finish']      = 1;
            $outData['excel_url']   = $fileName;
        }

        return $outData;

    }

    public function saveExcel($jobId,$title,$excelData,$page){

        if(empty($excelData)){
            throw new \Exception('导出数据为空');
        }

        $fileName = $oldFile = Cache::get($jobId) ?: $jobId . '.xlsx';

        $filePath = public_path('excel');
        if(!is_dir($filePath)){
            mkdir($filePath);
        }

        if(!file_exists($filePath .'/'. $fileName)){
            $filePath .= '/' . $fileName;
            $spreadsheet = new Spreadsheet();
            $spreadsheet->getActiveSheet()->fromArray($title, null, "A1");
        }else{
            $spreadsheet = IOFactory::load($filePath .'/'. $fileName);
            $fileName = "{$jobId}-{$page}.xlsx";
            $filePath .= '/' . $fileName;
        }

        $sheet = $spreadsheet->getActiveSheet();

        $row = $sheet->getHighestRow()+1;
        $sheet->fromArray($excelData, null, "A{$row}");

        /*$sheet->insertNewRowBefore($row);
        foreach ($cellData['data'] as $cellItem){
            $sheet->setCellValue('A'.$row, $cellItem['fmaterialname1']);
            $row++;
        }*/

        $writer = IOFactory::createWriter($spreadsheet,'Xlsx');
        $writer->save($filePath);

        //@unlink($oldFile);

        Cache::set($jobId,$fileName,7200);

        return env('APP_URL') . '/excel/' . $fileName;
    }

}
